package com.newdjk.newdoctor.ui;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.GlideUtils;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.MedicationCompanyEntity;
import com.newdjk.okhttp.entity.OrganizationInfoEntity;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/*
 *  @项目名：  Doctor
 *  @包名：    com.newdjk.doctor.ui.activity
 *  @文件名:   MyPointsActivity
 *  @创建者:   huhai
 *  @创建时间:  2019/1/21 9:45
 *  @描述：
 */
public class ShareShopActivity extends BasActivity implements IWXAPIEventHandler, View.OnClickListener {
    private static final String TAG = "ShareShopActivity";
    @BindView(R.id.im_preview)
    ImageView imPreview;
    @BindView(R.id.tv_hospitical_name)
    TextView tvHospiticalName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.qr_code)
    ImageView qrCode;
    @BindView(R.id.tv_url)
    TextView tvUrl;
    @BindView(R.id.btn_share)
    TextView btnShare;
    @BindView(R.id.lv_share_view)
    LinearLayout lvShareView;


    private IWXAPI iwxapi;
    private String APP_ID = "wxa3553079f33d6583";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_share:
                showBottomDialog();

                break;
            case R.id.mWechatFriend:
                share(SHARE_TYPE.Type_WXSceneSession);
                mDialog.dismiss();
                break;
            case R.id.mWechatZone:
                share(SHARE_TYPE.Type_WXSceneTimeline);
                mDialog.dismiss();
                break;
            case R.id.mCancel:
                if (mDialog.isShowing())
                    mDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    enum SHARE_TYPE {Type_WXSceneSession, Type_WXSceneTimeline}

    private Dialog mDialog;
    private View mInflate;
    private LinearLayout mFriend, mZoom;
    private TextView mTvCancel;

    @Override
    protected String setTitle() {
        return "分享店铺";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_share_shop;
    }


    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected void initView() {

        iwxapi = WXAPIFactory.createWXAPI(ShareShopActivity.this, Contants.WEIXIN_APP_ID, false);
        iwxapi.handleIntent(this.getIntent(), this);

    }

    @Override
    protected void initListener() {
        btnShare.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        GetMedicationCompanyByDrId();

    }

    private void GetMedicationCompanyByDrId() {
//        if (null!=MyApplication.LoginEntity.getUser()){
//        NetServices.Factory.getService().GetMedicationCompanyByDrId(MyApplication.LoginEntity.getUser().getDoctorId(), "3").subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseComPleteObserver<MedicationCompanyEntity>(this) {
//
//                    @Override
//                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
//                        super.onFailure(e, erroressage, isNetWorkError);
//                    }
//
//                    @Override
//                    protected void onSuccees(BaseEntity<MedicationCompanyEntity> t) throws Exception {
//
//                        if (t.getData() != null) {
//
//
//                        }
//
//
//                    }
//                });
//
//        }
        if (MyApplication.LoginEntity.getUser().getOrgId().size() >0) {
            QueryOrganizationInfoByOrgId(MyApplication.LoginEntity.getUser().getOrgId().get(0));
        }

    }

    private void QueryOrganizationInfoByOrgId(int orgId) {

        NetServices.Factory.getService().QueryOrganizationInfoByOrgId(orgId, 0).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<OrganizationInfoEntity>() {
                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);
                    }

                    @Override
                    protected void onSuccees(BaseEntity<OrganizationInfoEntity> t) throws Exception {
                        GlideUtils.loadCommonmage(t.getData().getPicturePath(), imPreview);
                        GlideUtils.loadCommonmage(t.getData().getOrgQRCode().getQRCodePath(), qrCode);
                        tvAddress.setText("地址:" + (TextUtils.isEmpty(t.getData().getOrdAddress()) ? "暂无" : t.getData().getOrdAddress()));
                        tvHospiticalName.setText(TextUtils.isEmpty(t.getData().getOrgName()) ? "" : t.getData().getOrgName());
                        tvTime.setText("营业时间:" + (TextUtils.isEmpty(t.getData().getServiceTime()) ? "暂无" : t.getData().getServiceTime()));
                    }
                });

    }

    private void getQRcode() {

    }


    public void showBottomDialog() {
        mDialog = new Dialog(ShareShopActivity.this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        mInflate = LayoutInflater.from(ShareShopActivity.this).inflate(R.layout.dialog_share, null);
        //初始化控件
        mFriend = mInflate.findViewById(R.id.mWechatFriend);
        mZoom = mInflate.findViewById(R.id.mWechatZone);
        mTvCancel = mInflate.findViewById(R.id.mCancel);
        mFriend.setOnClickListener(this);
        mZoom.setOnClickListener(this);
        mTvCancel.setOnClickListener(this);
        //将布局设置给Dialog
        mDialog.setContentView(mInflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 10;//设置Dialog距离底部的距离
//       将属性设置给窗体
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        mDialog.show();//显示对话框
    }


    private void share(SHARE_TYPE type) {
      /*  FileInputStream fis = null;
        try {
            fis = new FileInputStream(mSdPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (fis == null){
            return;
        }
        Bitmap thumb  = BitmapFactory.decodeStream(fis);*/

//        WXWebpageObject webpageObject = new WXWebpageObject();
//        webpageObject.webpageUrl = tvUrl.getText() + "";
//        //用WXWebpageObject对象初始化一个WXMediaMessage，天下标题，描述
//        WXMediaMessage msg = new WXMediaMessage(webpageObject);
//        msg.title = "芸医生医护版邀请函";
//        msg.description = "芸医生为用户提供咨询、续方、复诊、康复护理、诊后随访等医疗健康服务";
//        //这块需要注意，图片的像素千万不要太大，不然的话会调不起来微信分享，
//        //我在做的时候和我们这的UIMM说随便给我一张图，她给了我一张1024*1024的图片
//        //当时也不知道什么原因，后来在我的机智之下换了一张像素小一点的图片好了！
//        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
//        msg.setThumbImage(thumb);
//
//         /* WXImageObject imageObject = new WXImageObject(bitmap);
//          WXMediaMessage msg = new WXMediaMessage();
//          msg.mediaObject = imageObject;*/
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = msg;
//
//        switch (type) {
//            case Type_WXSceneSession:
//                req.scene = SendMessageToWX.Req.WXSceneSession;
//                break;
//            case Type_WXSceneTimeline:
//                req.scene = SendMessageToWX.Req.WXSceneTimeline;
//                break;
//        }
        Bitmap bitmap = viewConversionBitmap(lvShareView);

        WXImageObject wxImageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap mBp = Bitmap.createScaledBitmap(bitmap, 120, 120, true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(mBp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//  transaction字段用
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;

        switch (type) {
            case Type_WXSceneSession:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Type_WXSceneTimeline:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
        }
        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result;
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = "分享成功";
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "取消分享";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "分享被拒绝";
                break;
            default:
                result = "发送返回";
                break;
        }
        Toast.makeText(ShareShopActivity.this, result, Toast.LENGTH_SHORT).show();
    }

    /**
     * view转bitmap
     */
    public Bitmap viewConversionBitmap(View view) {
        Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        view.draw(c);
        return bmp;
    }
}
